package com.alibaba.nacos.console.config;

import lombok.extern.slf4j.Slf4j;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * @Author 爱做梦的奋斗青年
 * @Date 2021/11/5
 * @Description
 */
@Slf4j
//@Configuration
public class FlywayConfig {

    @Autowired
    private DataSource dataSource;

    @PostConstruct
    public void migrate() {
        Flyway flyway = Flyway.configure()
                .dataSource(dataSource)
                .locations("db")
                .baselineOnMigrate(true)
                .outOfOrder(true)
                .encoding("UTF-8")
                .load();
        try {
            flyway.migrate();
        } catch (FlywayException e) {
            log.error("Flyway配置第一次加载出错", e);
            try {
                flyway.repair();
                log.info("Flyway配置修复成功");
                flyway.migrate();
                log.info("Flyway配置重新加载成功");
            } catch (Exception e1) {
                log.error("Flyway配置第二次加载出错", e1);
                throw e1;
            }
        }
    }
}
